<!--
/**
 * 单元名称：TemplateMessage
 * 单元功能：资讯管理/模板消息
 * 所属模块功能：资讯管理/模板消息
 * 创建人：liang
 * 创建时间：231130
 * 修改人：
 * 修改时间：
 */
 -->
<template>
  <div style="height: 100%;">
    <m-page-list
      ref="pageListRef"
      :option="option"
      :page="page"
      :total="total"
      :table-data="tableData"
      :table-loading="tableLoading"
      v-model:value="query"
      @h-btn-click="hBtnClick"
      @col-btn-click="colBtnClick"
      @search-data="searchData"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="diaShow" :title="dia.title" :close-on-click-modal="false" draggable destroy-on-close align-center ref="diaRef">
      <el-scrollbar max-height="70vh">
        <el-form ref="formRef" class="form-wrap" label-width="130" scroll-to-error :model="ruleForm">
          <el-col :span="(item.col || 1) * 6" v-for="(item, i) in dialogOption.fieldList" :key="i" v-show="!item.hide">
            <el-form-item
              :label="item.label"
              class="form-item-wrap"
              :prop="item.field_id"
              :rules="[{ required: item.required, message: item.requiredMsg || (item.label + '不能为空'), trigger: 'blur'}, ...(item.rules || [])]"
            >
              <m-form-item v-if="item.field_id !== 'members'" :id="item.field_id" :field="item" v-bind="$attrs" :value="mValue[item.field_id]" @m-change.self="handleChange"/>
              <template v-else>
                <m-customer-select :m-value="mValue" :rule-form="ruleForm" :item="item"></m-customer-select>
                <el-select
                  v-if="false"
                  popper-class="custom-option-popper"
                  v-model="mValue[item.field_id]"
                  placeholder="请选择"
                  style="width: 100%;"
                  no-data-text="没有数据"
                  clearable
                  :multiple="true"
                >
                  <!-- <template #header> 2.4.3版本新加，当前2.3.3不可用
                    <el-checkbox
                      v-model="item.checkAll"
                      :indeterminate="item.indeterminate"
                      @change="(val) => onCheckAll(val, item)"
                    >全选</el-checkbox>
                  </template> -->
                  <el-option
                    v-for="(opt, o) in item.options"
                    :key="o"
                    :label="opt[item.optionName || 'label']"
                    :value="opt[item.optionId || 'value']"
                  >
                    <!-- <span style="float: left">{{ opt.label }}</span>
                    <span style=" float: right; color: var(--el-text-color-secondary); font-size: 13px;">{{ opt.value }}</span> -->
                    <div>
                      <div class="custom-option-wrap">
                        <div class="name">{{ opt.customer_name }}</div>
                        <div class="phone">{{ opt.phone }}</div>
                      </div>
                      <div class="openid">{{ opt.customer_id }}</div>
                    </div>
                  </el-option>
                </el-select>
                <!-- <el-checkbox
                  class="all-check"
                  v-model="item.checkAll"
                  :indeterminate="item.indeterminate"
                  @change="(val) => onCheckAll(val, item)"
                >全选</el-checkbox> -->
              </template>
              <el-checkbox
                v-if="item.field_id === 'shuttle_id'"
                class="all-check"
                v-model="item.checkAll"
                @change="onRefreshCustomerList(item)"
              >按班车查询客户</el-checkbox>

            </el-form-item>
          </el-col>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onDiaClose">取消</el-button>
          <el-button type="primary" @click="onDiaConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发送弹窗 -->
    <el-dialog class="sas" v-model="sendShow" title="模板信息通知发送" :close-on-click-modal="false" draggable destroy-on-close align-center ref="sendDiaRef">
      <el-scrollbar max-height="70vh">
        <el-form ref="sendFormRef" class="form-wrap" label-width="130" scroll-to-error :model="sendForm">
          <el-col :span="(item.col || 1) * 6" v-for="(item, i) in sendFieldList" :key="i">
            <el-form-item
              :label="item.label"
              class="form-item-wrap"
              :prop="item.field_id"
              :rules="[{ required: item.required, message: item.requiredMsg || (item.label + '不能为空'), trigger: 'blur'}]"
            >
              <m-form-item v-if="item.field_id !== 'members'" :id="item.field_id" :field="item" v-bind="$attrs" :value="sValue[item.field_id]" @m-change.self="onSendChange"/>
              <m-customer-select v-else :m-value="sValue" :rule-form="sendForm" :item="item" />
              <el-checkbox
                v-if="item.field_id === 'shuttle_id'"
                class="all-check"
                v-model="item.checkAll"
                @change="onSendRefreshCustomerList(item)"
              >按班车查询客户</el-checkbox>
            </el-form-item>
          </el-col>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onSendClose">取消</el-button>
          <el-button type="primary" @click="onSendConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, } from 'vue'
import { useRouter, } from 'vue-router'

// 组件
import MPageList from '@/components/PageList'
import MDialogForm from '@/components/DialogForm/DialogForm'
import MFormItem from '@/components/common/Form/FormItem'
import MCustomerSelect from './components/CustomerSelect'
// 请求
import {
  getAllServiceMessageQueryData, getAllInfoArticeQueryDataAll, getAllServiceMessageQueryTmplList, getAllServiceMessageQueryTmplCont,
  getAllServiceMessageQueryTmplsendCustomers, postAllServiceMessage, putAllServiceMessage, getAllServiceMessage,
  delAllServiceMessage, postAllServiceMessageTmplSendBatch, postAllServiceMessageTmplSendQueue,
} from '@/request/api/wechatTweet'

import { usePageList, } from '../../composables/pageList'
import { refOpt, } from '@/pages/const'
import { ElMessage, ElMessageBox, ElLoading, } from 'element-plus'

import { usePublicCompo, } from './composables/public'

const router = useRouter()

const {
  opts,
  option, page, total, tableLoading, tableData, query, dialogRef, dialogShow, dialogData, dialogOption,
  hBtnClick, colBtnClick, searchData, getDataList, dialogConfirm,
  getDataPage,
} = usePageListCompo()

const {
  diaRef,
  pageListRef, pageLoading,
  diaLoading, dia, diaShow, formRef, ruleForm, mValue,
  onCheckAll, onRefreshCustomerList, onDiaConfirm, onDiaClose, handleChange,
} = useCustomDiaCompo(option, dialogOption)

const {
  sendDiaRef,
  sendShow, sendLoading, sendFormRef, sendForm, sendFieldList, sValue,
  onSendChange, onSendConfirm, onSendClose, onSendRefreshCustomerList,
} = useSendDiaCompo(option)


function usePageListCompo() {
  let opts = {
        auth_id: '',
        idKey: 'row_id',
        getApi: getDataPage,
        delApi: delData,
      },
      {
        option, page, total, tableLoading, tableData, query, dialogRef, dialogShow, dialogData, dialogOption,
        hBtnClick, colBtnClick, searchData, getDataList, dialogConfirm,
      } = usePageList(opts)

  setOption()
  function setOption() {
    // 设置查询条件
    option.conditions = [
      { label: '关键词',type: 'text',field_id: 'keyword',col: 12},
      { label: '状态',type: 'picklist',field_id: 'state',col: 12,options: [
        {name: '启用',id: '1'},
        {name: '停用',id: '0'},
      ]},
    ]
    option.tableSelection = true;


    // 设置表头
    option.cols = [
      { prop: 'title', label: '标题', },
      { prop: 'template_id', label: '模板编号', },
      { prop: 'is_all_customer', label: '全部客户', type: 'bool', },
      { prop: 'shuttle_id', label: '班车号', },
      { prop: 'url', label: '推文链接', },
      { prop: 'state', label: '使用状态', type: 'bool', },
      { prop: 'input_name', label: '录入员名' },
      { prop: 'input_time', label: '录入时间' },
      { prop: 'modify_id', label: '修改员号' },
      { prop: 'modify_name', label: '修改员名' },
      { prop: 'modify_time', label: '修改时间' },
    ]

    option.titleList = [
      { name: '模板消息', path: '/tmplmsg', },
      { name: '发送记录', path: '/sendrec', },
    ]

    dialogOption.fieldList = [
      { field_id: 'title', show_field: 'title', label: '标题', type: 'text', col: 3, required: true, },
      { field_id: 'artice_id', show_field: 'artice_id', label: '文章推文', type: 'picklist', col: 3, required: true, options: [], optionId: 'artice_id', optionName: 'title', api: getAllInfoArticeQueryDataAll, filterable: true, },
      { field_id: 'is_all_customer', show_field: 'is_all_customer', label: '全部客户', type: 'bool', col: 3, },
      { ...refOpt.shuttle_name, field_id: 'shuttle_id', show_field: 'shuttle_id', label: '班车号', required: false, col: 3, checkAll: false, },
      { field_id: 'members', show_field: 'members', label: '客户', type: 'multiple', col: 3, required: false, options: [], optionId: 'customer_id', optionName: 'customer_name', api: getAllServiceMessageQueryTmplsendCustomers, filterable: true, checkAll: false, },
      {
        field_id: 'template_id', show_field: 'template_id', label: '消息模板', type: 'picklist', col: 3, required: true, options: [], optionId: 'template_id',
        optionName: 'title', api: getAllServiceMessageQueryTmplList, filterable: true, checkAll: false, indeterminate: false,
      },
      { field_id: 'keyword1', show_field: 'keyword1', label: '关键词1', type: 'text', col: 3, required: true, hide: true, rules: [], },
      { field_id: 'keyword2', show_field: 'keyword2', label: '关键词2', type: 'text', col: 3, required: true, hide: true, },
      { field_id: 'keyword3', show_field: 'keyword3', label: '关键词3', type: 'text', col: 3, required: true, hide: true, },
      { field_id: 'keyword4', show_field: 'keyword4', label: '关键词4', type: 'text', col: 3, required: true, hide: true, },
      { field_id: 'keyword5', show_field: 'keyword5', label: '关键词5', type: 'text', col: 3, required: true, hide: true, },
      { field_id: 'url', show_field: 'url', label: '跳转链接', type: 'text', col: 3, },
      { field_id: 'state', show_field: 'state', label: '使用状态', type: 'bool', col: 3, },
      { field_id: 'remark', show_field: 'remark', label: '备注', type: 'textarea', col: 3, },
    ]
    dialogOption.center = true
  }

  let pageParams = {}
  function getDataPage(d) {
    if(d) {
      pageParams = d
    } else {
      pageParams['page.no'] = 1
      d = pageParams
    }
    return new Promise(resolve => {
      let data = {
        ...d,
      }
      delete data['page.no']
      delete data['page.size']
      data.pagenumber = d['page.no']
      data.pagesize = d['page.size']
      if(data.state) data.state = data.state === '1'
      getAllServiceMessageQueryData(data).then(res => {
        if(res?.errcode === 0) {
          console.log(res);
          res?.row.forEach(item => {
            item.state = item.state ? '启用' : '停用'
          })
        }
        resolve(res)
      })
    })
  }
  function delData(id) {
    return new Promise(resolve => {
      delAllServiceMessage(`${opts.idKey}=${id}`).then(res => resolve(res))
    })
  }

  return {
    opts,
    option, page, total, tableLoading, tableData, query, dialogRef, dialogShow, dialogData, dialogOption,
    hBtnClick, colBtnClick, searchData, getDataList, dialogConfirm,
    getDataPage,
  }
}

function useCustomDiaCompo(option, dialogOption) {
  let pageListRef = ref(null),
      pageLoading = ref(false),
      diaLoading = ref(true),
      dia = reactive({
        title: '新增',
      }),
      diaShow = ref(false),
      formRef = ref(null),
      ruleForm = reactive({}),
      mValue = reactive({}),
      wechatKeywordValidtor = {
        thing: {
          validator(rule, value, callback) {
            if(value.length > 20) {
              return callback(new Error('20个以内字符'))
            }
            callback()
          },
          trigger: 'blur',
        },
        character_string: {
          validator(rule, value, callback) {
            // 不能包含中文
            let reg = /[\u4E00-\u9FFF]/g
            if(value.length > 32 || reg.test(value)) {
              return callback(new Error('32位以内数字、字母或符号'))
            }
            callback()
          },
          trigger: 'blur',
        },
        time: {
          validator(rule, value, callback) {
            if(value) {
              console.log(value, 'time valid')
              let valid = validTimeKw(value)
              if(valid) {
                return callback()
              } else {
                return callback(new Error('格式不正确'))
              }
            }
            callback()
          },
          trigger: 'blur',
        },
        amount: {
          validator(rule, value, callback) {
            let reg = /^\d{1,12}(\.\d{1,2})?(元)?$/
            if(value && !reg.test(value)) {
              return callback(new Error('12位以内纯数字，可带小数，结尾可带“元”'))
            }
            callback()
          },
          trigger: 'blur',
        },
        phone_number: {
          validator(rule, value, callback) {
            let telReg = /^((\+)?\d{1,4}-)?(\d{1,4}-)?\d{7,8}$/,
                phoneReg = /^1[3456789]\d{9}$/
            if(value && !(telReg.test(value) || phoneReg.test(value))) {
              return callback(new Error('请输入17位以内的电话号码，例：+86-0766-66888866、13512345678'))
            }
            callback()
          },
          trigger: 'blur',
        },
        car_number: {
          validator(rule, value, callback) {
            let reg = /^([\u4e00-\u9fa5]{1})?([0-9A-Z]+)([\u4e00-\u9fa5]{1})?$/
            if(value.length > 8 || (value && !reg.test(value))) {
              return callback(new Error('请输入8位以内的车牌号码，第一位与最后一位可为汉字，其余为字母或数字'))
            }
            callback()
          },
          trigger: 'blur',
        },
        const: {
          validator(rule, value, callback) {
            if(value.length > 20) {
              return callback(new Error('请输入20位以内字符'))
            }
            callback()
          },
          trigger: 'blur',
        },
      },
      diaRef = ref(null)

  let { getDiaAllSelect, getDetlData, } = usePublicCompo()

  watch(() => mValue.template_id, (newVal, oldVal) => {
    if(newVal) getTmplContent(newVal)
  })

  resetHlBtns()
  resetColBtns()
  setMValueKey()
  function resetHlBtns() {
    option.hLBtns = [
      { title: '新增', id: 'newData', type: 'primary', event: onNewData, },
      { title: '批量删除', id: 'batchDel', type: 'danger', event: onBatchDel, },
    ]
  }
  function resetColBtns() {
    option.colBtns.filter(item => item.id === 'edit').forEach(item => {
      item.event = onRowEdit
    })
  }
  function setMValueKey() {
    Object.keys(mValue).forEach(key => {
      delete mValue[key]
      delete ruleForm[key]
    })
    dialogOption.fieldList.forEach(item => {
      let { field_id, type, } = item
      if(field_id.indexOf('keyword') === 0) {
        item.required = false
        item.hide = true
        item.rules = []
      }
      let val = ''
      if(field_id === 'members') val = []
      mValue[field_id] = field_id === 'is_all_customer' ? false : type === 'bool' ? true : val
      ruleForm[field_id] = field_id === 'is_all_customer' ? false : type === 'bool' ? true : val
    })
    mValue.row_id = 0
    ruleForm.row_id = 0
  }
  function validDate(arr) {
    let [ year, month, day, ] = arr
    if(year < 1900) return false
    if(month > 12) return false
    if(day > new Date(year, month, 0).getDate()) return false
    return true
  }
  function validTime(arr) {
    let [ hour, minute, ] = arr
    if(hour > 23) return false
    if(minute > 59) return false
    return true
  }
  function validTimeKw(val) {
    let dateReg1 = /^\d{4}-\d{1,2}-\d{1,2}$/,
        dateReg2 = /^\d{4}\/\d{1,2}\/\d{1,2}$/,
        dateReg3 = /^\d{4}年\d{1,2}月\d{1,2}日$/,
        timeReg1 = /^\d{1,2}:\d{1,2}$/,
        timeReg2 = /^\d{1,2}时\d{1,2}分$/,
        dtReg1 = /^\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}$/,
        dtReg2 = /^\d{4}\/\d{1,2}\/\d{1,2} \d{1,2}:\d{1,2}$/,
        dtReg3 = /^\d{4}年\d{1,2}月\d{1,2}日 \d{1,2}时\d{1,2}分$/

    if(val.indexOf('~') > -1) { // 范围
      let range = val.split('~')
      if(range.length !== 2) {
        return false
      } else {
        let hasBlank = 0,
            d1 = 0,
            d2 = 0,
            d3 = 0,
            t1 = 0,
            t2 = 0,
            dt1 = 0,
            dt2 = 0,
            dt3 = 0
        range.forEach(item => {
          if(item.indexOf(' ') > -1) hasBlank++

          if(dateReg1.test(item)) d1++;
          else if(dateReg2.test(item)) d2++;
          else if(dateReg3.test(item)) d3++;
          else if(timeReg1.test(item)) t1++;
          else if(timeReg2.test(item)) t2++;
          else if(dtReg1.test(item)) dt1++;
          else if(dtReg2.test(item)) dt2++;
          else if(dtReg3.test(item)) dt3++;
        })
        if(hasBlank === 1) return false
        if(![d1, d2, d3, t1, t2, dt1, dt2, dt3].includes(2)) return false
      }

      let valid = true
      range.forEach(item => {
        let pass = validTimeKw(item)
        if(!pass) valid = pass
      })
      return valid
    } else {
      if(dateReg1.test(val) || dateReg2.test(val) || dateReg3.test(val)) {  // 日期格式
        let arr = val.replace(/\//, '-').replace('年', '-').replace('月', '-').replace('日', '').split('-'),
            valid = validDate(arr)
        return valid
      } else if(timeReg1.test(val) || timeReg2.test(val)) { // 时间格式
        let arr = val.replace('时', ':').replace('分', '').split(':'),
            valid = validTime(arr)
        return valid
      } else if(dtReg1.test(val) || dtReg2.test(val) || dtReg3.test(val)) { // 日期时间格式
        let [ date, time, ] = val.split(' '),
            dArr = date.replace(/\//, '-').replace('年', '-').replace('月', '-').replace('日', '').split('-'),
            tArr = time.replace('时', ':').replace('分', '').split(':'),
            dValid = validDate(dArr),
            tValid = validTime(tArr)
        return dValid && tValid
      } else {
        return false
      }
    }
  }

  // 全选
  function onCheckAll(val, item) {
    item.indeterminate = false
    let { field_id, options, optionId, optionName, } = item
    if(val) {
      mValue[field_id] = options.map(opt => opt[optionId])
    } else {
      mValue[field_id] = []
    }
  }
  function onRefreshCustomerList(item) {
    let checked = item.checkAll,
        id = ruleForm[item.field_id],
        params = {
          is_all_customer: 1,
          shuttle_id: id,
        }
    if(checked) { // 按班车查询客户
      if(item.searchId === id) return
      item.searchId = id
      if(id) {
        params.is_all_customer = 0
        params.shuttle_id = id
      } else {
        delete params.shuttle_id
      }
    } else {
      if(!item.searchId) return
      item.searchId = ''
      // params.shuttle_id = ''
      delete params.shuttle_id
    }

    dialogOption.fieldList.filter(item => item.field_id === 'members').forEach(item => {
        let { api, field_id, optionId, } = item
        api(params).then(res => {
          if(res.errcode === 0) {
            item.options = res.row

            let currVal = ruleForm[field_id],
                filterVal = []
            res.row.forEach(item => {
              if(currVal.includes(item[optionId])) filterVal.push(item[optionId])
            })
            mValue[field_id] = filterVal
            ruleForm[field_id] = filterVal
          }
        })
      })
  }
  // 新增
  function onNewData() {
    if(mValue.row_id) setMValueKey()
    diaShow.value = true
    dialogOption.fieldList.filter(item => item.field_id === 'shuttle_id').forEach(item => {
      item.checkAll = false
      item.searchId = ''
    })

    // diaLoading.value = true
    let loadInst = null
    nextTick(() => {
      loadInst = ElLoading.service({
        target: diaRef.value.$el.nextElementSibling.querySelector('.el-dialog'),
      })
    })

    dia.title = '新增'
    getDiaAllSelect(dialogOption.fieldList).then(res => {
      // diaLoading.value = false
      loadInst && loadInst.close()
    })
  }
  function onBatchDel() {
    let rows = pageListRef.value.getSelectionRows();
    if(!rows.length) {
      ElMessage({type: 'warning', message: '请先选择数据行'});
      return;
    }
    ElMessageBox.confirm('确定删除所选数据？', '批量删除', {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: (action) => {
        if (action === 'confirm'){
          pageLoading.value = true;

          let ids = []
          rows.forEach(item => ids.push(item.row_id))
          delAllServiceMessage(`row_id=${ids.join(',')}`).then(res => {
            pageLoading.value = false;
            if(res.errcode !== 0) return
            ElMessage({
              type: 'success',
              message: `删除成功`,
            });
            getDataList();
          })
        }
      },
    })
  }
  // 表格编辑
  function onRowEdit(scope, eventId) {
    let { row, } = scope
    diaShow.value = true

    // diaLoading.value = true
    let loadInst = null
    nextTick(() => {
      loadInst = ElLoading.service({
        target: diaRef.value.$el.nextElementSibling.querySelector('.el-dialog'),
      })
    })
    dia.title = '编辑'
    Promise.all([getDetlData(row), getDiaAllSelect(dialogOption.fieldList)]).then(res => {
      if(res[0]) {
        Object.keys(mValue).forEach(key => {
          let val = res[0][key]
          mValue[key] = val === undefined ? '' : val
          ruleForm[key] = val === undefined ? '' : val
        })
      }

      // diaLoading.value = false
      loadInst && loadInst.close()
    })
  }

  // 确定
  function onDiaConfirm() {
    formRef.value?.validate(valid => {
      if(valid) { // 验证通过
        let isEdit = mValue.row_id ? true : false,
            reqFn = isEdit ? updateData : saveData

        // diaLoading.value = true
        let loadInst = ElLoading.service({
          target: diaRef.value.$el.nextElementSibling.querySelector('.el-dialog'),
        })
        let { shuttle_id, is_all_customer, members, } = ruleForm
        if(!is_all_customer && (!shuttle_id && !members.length)) {
          ElMessage.warning('请选择班车号或客户！')
          return
        }
        reqFn().then(res => {
          // diaLoading.value = false
          loadInst.close()
          if(res.errcode !== 0) return
          ElMessage.success(`${isEdit ? '编辑' : '保存'}成功！`)
          onDiaClose()
          getDataList()
          setMValueKey()
        })
      }
    })
  }

  // 取消
  function onDiaClose() {
    diaShow.value = false
  }
  function handleChange(valueObj, id) {
    if(mValue[id] !== undefined) {
      mValue[id] = valueObj[id]
      ruleForm[id] = valueObj[id]
      // formRef.value?.clearValidate(id)

      if(id === 'shuttle_id') onRefreshCustomerList(dialogOption.fieldList.filter(item => item.field_id === id)[0])
    }
  }


  // 接口
  function getTmplContent(id) {
    getAllServiceMessageQueryTmplCont({
      template_id: id,
    }).then(res => {
      if(res.errcode !== 0) return
      let { row, } = res

      let keywordFields = dialogOption.fieldList.filter(item => !item.field_id.indexOf('keyword'))
      keywordFields.forEach(item => {
        item.hide = true
        item.required = false
        item.rules = []
        item.placeholder = ''
        formRef.value?.clearValidate(item.field_id)
      })
      row.forEach((item, i) => {
        let { field_id, field_name, } = item,
            kwField = keywordFields[i]

        kwField.label = field_name
        kwField.hide = false
        kwField.required = true

        /**
         * 模板消息：关键字填写类型说明
         * 官方文档：https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html
         * { 参数类别: thing, 参数说明: 事物, 参数值限制: 20个以内字符, 说明: 可汉字、数字、字母或符号组合, }
         * { 参数类别: character_string, 参数说明: 字符串	, 参数值限制: 32位以内数字、字母或符号, 说明: 可数字、字母或符号组合, }
         * { 参数类别: time, 参数说明: 时间, 参数值限制: 24小时制时间格式（支持+年月日），支持填时间段，两个时间点之间用“~”符号连接, 说明: 例如：15:01，或：2019年10月1日 15:01, }
         * { 参数类别: amount, 参数说明: 金额, 参数值限制: 1个币种符号+12位以内纯数字，可带小数，结尾可带“元”, 说明: 可带小数, }
         * { 参数类别: phone_number, 参数说明: 电话, 参数值限制: 17位以内，数字、符号, 说明: 电话号码，例：+86-0766-66888866, }
         * { 参数类别: car_number, 参数说明: 车牌, 参数值限制: 8位以内，第一位与最后一位可为汉字，其余为字母或数字, 说明: 车牌号码：粤A8Z888挂, }
         * { 参数类别: const, 参数说明: 常量, 参数值限制: 20位以内字符，超过无法下发注：需枚举（需将内容提交平台审核，审核通过可下发）, 说明: 只能下发审核通过的字符串和空串, }
         */
        let validtorKey = ''
        if(field_id.indexOf('thing') === 0) {
          validtorKey = 'thing'
          // kwField.rules = [ wechatKeywordValidtor.thing, ]
          kwField.placeholder = '请输入20个以内字符，可汉字、数字、字母或符号组合'
        } else if(field_id.indexOf('character_string') === 0) {
          validtorKey = 'character_string'
          // kwField.rules = [ wechatKeywordValidtor.character_string, ]
          kwField.placeholder = '请输入32位以内数字、字母或符号'
        } else if(field_id.indexOf('time') === 0) {
          validtorKey = 'time'
          kwField.placeholder = '请输入24小时制时间格式（支持+年月日），支持填时间段，两个时间点之间用“~”符号连接'
        } else if(field_id.indexOf('amount') === 0) {
          validtorKey = 'amount'
          kwField.placeholder = '12位以内纯数字，可带小数，结尾可带“元”'
        } else if(field_id.indexOf('phone_number') === 0) {
          validtorKey = 'phone_number'
          kwField.placeholder = '请输入17位以内，数字、符号的电话号码，例：+86-0766-66888866'
        } else if(field_id.indexOf('car_number') === 0) {
          validtorKey = 'car_number'
          kwField.placeholder = '请输入8位以内，第一位与最后一位可为汉字，其余为字母或数字的车牌号码'
        } else if(field_id.indexOf('const') === 0) {
          validtorKey = 'const'
          kwField.placeholder = '请输入20位以内字符'
        } /* else if(field_id.indexOf('keyword') === 0) {
          kwField.placeholder = '请输入19位以内字符'
        } */ else {
          kwField.placeholder = '请输入19位以内字符'
        }
        if(validtorKey && wechatKeywordValidtor[validtorKey]) {
          kwField.rules = [ wechatKeywordValidtor[validtorKey], ]
        }
      })
    })
  }
  function saveData() {
    let { members, } = ruleForm,
        data = {
          ...ruleForm,
          members: members.join(','),
        }
    return new Promise(resolve => {
      postAllServiceMessage(data).then(res => {
        resolve(res)
      })
    })
  }
  function updateData() {
    let { members, } = ruleForm,
        data = {
          ...ruleForm,
          members: members.join(','),
        }
    return new Promise(resolve => {
      putAllServiceMessage(data).then(res => {
        resolve(res)
      })
    })
  }

  return {
    diaRef,
    pageListRef,
    diaLoading,
    dia,
    diaShow,
    formRef,
    ruleForm,
    mValue,
    onCheckAll,
    onRefreshCustomerList,
    onDiaConfirm,
    onDiaClose,
    handleChange,
  }
}

function useSendDiaCompo(option) {
  let sendDiaRef = ref(false),
      sendShow = ref(false),
      sendLoading = ref(false),
      sendFormRef = ref(null),
      defaultForm = {
        row_id: 0,
        title: '',
        sendType: 'batch',
        is_all_customer: true,
        shuttle_id: '',
        members: [],
      },
      sendForm = reactive(JSON.parse(JSON.stringify(defaultForm))),
      sendFieldList = reactive([
        { field_id: 'title', show_field: 'title', label: '模板', type: 'text', col: 3, disabled: true, },
        { field_id: 'sendType', show_field: 'sendType', label: '发送方式', type: 'picklist', col: 3, required: true, options: [
          { value: 'batch', label: '批量发送', },
          { value: 'queue', label: '队列发送', },
        ], optionId: 'value', optionName: 'label', },
        { field_id: 'is_all_customer', show_field: 'is_all_customer', label: '全部客户', type: 'bool', col: 3, value: { is_all_customer: false, }, },
        { ...refOpt.shuttle_name, field_id: 'shuttle_id', show_field: 'shuttle_id', label: '班车号', required: false, col: 3, checkAll: false, },
        { field_id: 'members', show_field: 'members', label: '客户', type: 'multiple', col: 3, required: false, options: [], optionId: 'customer_id', optionName: 'customer_name', api: getAllServiceMessageQueryTmplsendCustomers, filterable: true, },
      ]),
      sValue = reactive(JSON.parse(JSON.stringify(defaultForm)))

  let { getDiaAllSelect, getDetlData, } = usePublicCompo()

  resetColBtns()
  function resetColBtns() {
    let pushColBtns = [
      { title: '发送', id: 'send', type: 'primary', event: onRowSend, },
      { title: '查看发送记录', id: 'sendRec', type: 'primary', event: onRowSendRec, },
    ]
    option.colBtns.push(...pushColBtns)
  }

  // 发送 onRowSend
  function onRowSend(scope, eventId) {
    let { row, } = scope
    sendShow.value = true
    sendFieldList.filter(item => item.field_id === 'shuttle_id').forEach(item => {
      item.checkAll = false
      item.searchId = ''
    })

    // sendLoading.value = true
    let loadInst = null
    nextTick(() => {
      loadInst = ElLoading.service({
        target: sendDiaRef.value.$el.nextElementSibling.querySelector('.el-dialog'),
      })
    })
    Promise.all([getDetlData(row), getDiaAllSelect(sendFieldList)]).then(res => {
      if(res[0]) {
        Object.keys(sValue).forEach(key => {
          let val = res[0][key]
          sValue[key] = val === undefined ? '' : val
          sendForm[key] = val === undefined ? '' : val
        })
        sValue.sendType = sendForm.sendType = defaultForm.sendType
      }

      // sendLoading.value = false
      loadInst && loadInst.close()
    })
  }
  // 查看发送记录 onRowSendRec
  function onRowSendRec(scope) {
    router.push({
      path: '/sendrec',
      query: { message_id: scope.row.message_id, },
    })
  }
  function onSendChange(valueObj, id) {
    if(sValue[id] !== undefined) {
      sValue[id] = valueObj[id]
      sendForm[id] = valueObj[id]
      // formRef.value?.clearValidate(id)
      if(id === 'shuttle_id') onSendRefreshCustomerList(sendFieldList.filter(item => item.field_id === id)[0])
    }
  }
  function onSendConfirm() {
    sendFormRef.value?.validate(valid => {
      if(valid) { // 验证通过
        let isBatch = sValue.sendType === 'batch',
            reqFn = isBatch ? postAllServiceMessageTmplSendBatch : postAllServiceMessageTmplSendQueue

        // sendLoading.value = true
        let loadInst = ElLoading.service({
          target: sendDiaRef.value.$el.nextElementSibling.querySelector('.el-dialog'),
        })

        let data = JSON.parse(JSON.stringify({ ...sValue, }))
        delete data.title
        delete data.sendType

        let { shuttle_id, is_all_customer, members, } = data
        if(!is_all_customer && (!shuttle_id && !members.length)) {
          ElMessage.warning('请选择班车号或客户！')
          return
        }
        reqFn(data).then(res => {
          // sendLoading.value = false
          loadInst.close()
          if(res.errcode !== 0) return
          ElMessage.success(`${isBatch ? '批量发送操作' : '添加发送队列'}成功！`)
          onSendClose()

          Object.entries(defaultForm).forEach(([key, val]) => {
            if(typeof val === 'object') {
              sendForm[key] = JSON.parse(JSON.stringify(val))
              sValue[key] = JSON.parse(JSON.stringify(val))
            } else {
              sendForm[key] = val
              sValue[key] = val
            }
          })
        })
      }
    })
  }
  function onSendClose() {
    sendShow.value = false
  }
  function onSendRefreshCustomerList(item) {
    let checked = item.checkAll,
        id = sendForm[item.field_id],
        params = {
          is_all_customer: 1,
          shuttle_id: id,
        }
    if(checked) { // 按班车查询客户
      if(item.searchId === id) return
      item.searchId = id
      if(id) {
        params.is_all_customer = 0
        params.shuttle_id = id
      } else {
        delete params.shuttle_id
      }
    } else {
      if(!item.searchId) return
      item.searchId = ''
      delete params.shuttle_id
    }

    sendFieldList.filter(item => item.field_id === 'members').forEach(item => {
      let { api, field_id, optionId, } = item
      api(params).then(res => {
        if(res.errcode === 0) {
          item.options = res.row

          let currVal = sendForm[field_id],
              filterVal = []
          res.row.forEach(item => {
            if(currVal.includes(item[optionId])) filterVal.push(item[optionId])
          })
          sValue[field_id] = filterVal
          sendForm[field_id] = filterVal
        }
      })
    })
  }


  return {
    sendDiaRef,
    sendShow,
    sendLoading,
    sendFormRef,
    sendForm,
    sendFieldList,
    sValue,
    onSendChange,
    onSendConfirm,
    onSendClose,
    onSendRefreshCustomerList,
  }
}
</script>

<style scoped lang='less'>
.custom-option-wrap {
  display: flex;
  flex-wrap: wrap;
  font-size: 13px;
  line-height: 32px !important;

  >.name {
    flex: 1;
  }
  >.phone {
    flex: 1;
    text-align: right;
  }
}
.openid {
  // line-height: normal !important;
  font-size: 13px;
  line-height: 32px !important;
  color: var(--el-color-info);
}

.form-item-wrap {
  position: relative;

  :deep(.all-check) {
    position: absolute;
    left: 100%;
    transform: translateX(10px);
  }
}
</style>
<style lang="less">
.custom-option-popper {
  .el-select-dropdown__item {
    height: unset !important;

    &.selected .openid{
      color: var(--el-color-primary);
    }
  }
}
</style>
